3 * Factory for handling the special page list and generating SpecialPage objects.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
22 * @defgroup SpecialPage SpecialPage
24 use MediaWiki\Linker\LinkRenderer
;
25 use Wikimedia\ObjectFactory
;
28 * Factory for handling the special page list and generating SpecialPage objects.
30 * To add a special page in an extension, add to $wgSpecialPages either
31 * an object instance or an array containing the name and constructor
32 * parameters. The latter is preferred for performance reasons.
34 * The object instantiated must be either an instance of SpecialPage or a
35 * sub-class thereof. It must have an execute() method, which sends the HTML
36 * for the special page to $wgOut. The parent class has an execute() method
37 * which distributes the call to the historical global functions. Additionally,
38 * execute() also checks if the user has the necessary access privileges
39 * and bails out if not.
41 * To add a core special page, use the similar static list in
42 * SpecialPageFactory::$list. To remove a core static special page at runtime, use
43 * a SpecialPage_initList hook.
45 * @ingroup SpecialPage
48 class SpecialPageFactory
{
50 * List of special page names to the subclass of SpecialPage which handles them.
52 private static $coreList = [
53 // Maintenance Reports
54 'BrokenRedirects' => BrokenRedirectsPage
::class,
55 'Deadendpages' => DeadendPagesPage
::class,
56 'DoubleRedirects' => DoubleRedirectsPage
::class,
57 'Longpages' => LongPagesPage
::class,
58 'Ancientpages' => AncientPagesPage
::class,
59 'Lonelypages' => LonelyPagesPage
::class,
60 'Fewestrevisions' => FewestrevisionsPage
::class,
61 'Withoutinterwiki' => WithoutInterwikiPage
::class,
62 'Protectedpages' => SpecialProtectedpages
::class,
63 'Protectedtitles' => SpecialProtectedtitles
::class,
64 'Shortpages' => ShortPagesPage
::class,
65 'Uncategorizedcategories' => UncategorizedCategoriesPage
::class,
66 'Uncategorizedimages' => UncategorizedImagesPage
::class,
67 'Uncategorizedpages' => UncategorizedPagesPage
::class,
68 'Uncategorizedtemplates' => UncategorizedTemplatesPage
::class,
69 'Unusedcategories' => UnusedCategoriesPage
::class,
70 'Unusedimages' => UnusedimagesPage
::class,
71 'Unusedtemplates' => UnusedtemplatesPage
::class,
72 'Unwatchedpages' => UnwatchedpagesPage
::class,
73 'Wantedcategories' => WantedCategoriesPage
::class,
74 'Wantedfiles' => WantedFilesPage
::class,
75 'Wantedpages' => WantedPagesPage
::class,
76 'Wantedtemplates' => WantedTemplatesPage
::class,
79 'Allpages' => SpecialAllPages
::class,
80 'Prefixindex' => SpecialPrefixindex
::class,
81 'Categories' => SpecialCategories
::class,
82 'Listredirects' => ListredirectsPage
::class,
83 'PagesWithProp' => SpecialPagesWithProp
::class,
84 'TrackingCategories' => SpecialTrackingCategories
::class,
87 'Userlogin' => SpecialUserLogin
::class,
88 'Userlogout' => SpecialUserLogout
::class,
89 'CreateAccount' => SpecialCreateAccount
::class,
90 'LinkAccounts' => SpecialLinkAccounts
::class,
91 'UnlinkAccounts' => SpecialUnlinkAccounts
::class,
92 'ChangeCredentials' => SpecialChangeCredentials
::class,
93 'RemoveCredentials' => SpecialRemoveCredentials
::class,
96 'Activeusers' => SpecialActiveUsers
::class,
97 'Block' => SpecialBlock
::class,
98 'Unblock' => SpecialUnblock
::class,
99 'BlockList' => SpecialBlockList
::class,
100 'AutoblockList' => SpecialAutoblockList
::class,
101 'ChangePassword' => SpecialChangePassword
::class,
102 'BotPasswords' => SpecialBotPasswords
::class,
103 'PasswordReset' => SpecialPasswordReset
::class,
104 'DeletedContributions' => DeletedContributionsPage
::class,
105 'Preferences' => SpecialPreferences
::class,
106 'ResetTokens' => SpecialResetTokens
::class,
107 'Contributions' => SpecialContributions
::class,
108 'Listgrouprights' => SpecialListGroupRights
::class,
109 'Listgrants' => SpecialListGrants
::class,
110 'Listusers' => SpecialListUsers
::class,
111 'Listadmins' => SpecialListAdmins
::class,
112 'Listbots' => SpecialListBots
::class,
113 'Userrights' => UserrightsPage
::class,
114 'EditWatchlist' => SpecialEditWatchlist
::class,
116 // Recent changes and logs
117 'Newimages' => SpecialNewFiles
::class,
118 'Log' => SpecialLog
::class,
119 'Watchlist' => SpecialWatchlist
::class,
120 'Newpages' => SpecialNewpages
::class,
121 'Recentchanges' => SpecialRecentChanges
::class,
122 'Recentchangeslinked' => SpecialRecentChangesLinked
::class,
123 'Tags' => SpecialTags
::class,
125 // Media reports and uploads
126 'Listfiles' => SpecialListFiles
::class,
127 'Filepath' => SpecialFilepath
::class,
128 'MediaStatistics' => MediaStatisticsPage
::class,
129 'MIMEsearch' => MIMEsearchPage
::class,
130 'FileDuplicateSearch' => FileDuplicateSearchPage
::class,
131 'Upload' => SpecialUpload
::class,
132 'UploadStash' => SpecialUploadStash
::class,
133 'ListDuplicatedFiles' => ListDuplicatedFilesPage
::class,
136 'ApiSandbox' => SpecialApiSandbox
::class,
137 'Statistics' => SpecialStatistics
::class,
138 'Allmessages' => SpecialAllMessages
::class,
139 'Version' => SpecialVersion
::class,
140 'Lockdb' => SpecialLockdb
::class,
141 'Unlockdb' => SpecialUnlockdb
::class,
143 // Redirecting special pages
144 'LinkSearch' => LinkSearchPage
::class,
145 'Randompage' => RandomPage
::class,
146 'RandomInCategory' => SpecialRandomInCategory
::class,
147 'Randomredirect' => SpecialRandomredirect
::class,
148 'Randomrootpage' => SpecialRandomrootpage
::class,
149 'GoToInterwiki' => SpecialGoToInterwiki
::class,
152 'Mostlinkedcategories' => MostlinkedCategoriesPage
::class,
153 'Mostimages' => MostimagesPage
::class,
154 'Mostinterwikis' => MostinterwikisPage
::class,
155 'Mostlinked' => MostlinkedPage
::class,
156 'Mostlinkedtemplates' => MostlinkedTemplatesPage
::class,
157 'Mostcategories' => MostcategoriesPage
::class,
158 'Mostrevisions' => MostrevisionsPage
::class,
161 'ComparePages' => SpecialComparePages
::class,
162 'Export' => SpecialExport
::class,
163 'Import' => SpecialImport
::class,
164 'Undelete' => SpecialUndelete
::class,
165 'Whatlinkshere' => SpecialWhatLinksHere
::class,
166 'MergeHistory' => SpecialMergeHistory
::class,
167 'ExpandTemplates' => SpecialExpandTemplates
::class,
170 'Booksources' => SpecialBookSources
::class,
172 // Unlisted / redirects
173 'ApiHelp' => SpecialApiHelp
::class,
174 'Blankpage' => SpecialBlankpage
::class,
175 'Diff' => SpecialDiff
::class,
176 'EditTags' => SpecialEditTags
::class,
177 'Emailuser' => SpecialEmailUser
::class,
178 'Movepage' => MovePageForm
::class,
179 'Mycontributions' => SpecialMycontributions
::class,
180 'MyLanguage' => SpecialMyLanguage
::class,
181 'Mypage' => SpecialMypage
::class,
182 'Mytalk' => SpecialMytalk
::class,
183 'Myuploads' => SpecialMyuploads
::class,
184 'AllMyUploads' => SpecialAllMyUploads
::class,
185 'PermanentLink' => SpecialPermanentLink
::class,
186 'Redirect' => SpecialRedirect
::class,
187 'Revisiondelete' => SpecialRevisionDelete
::class,
188 'RunJobs' => SpecialRunJobs
::class,
189 'Specialpages' => SpecialSpecialpages
::class,
190 'PageData' => SpecialPageData
::class,
193 private static $list;
194 private static $aliases;
197 * Reset the internal list of special pages. Useful when changing $wgSpecialPages after
198 * the internal list has already been initialized, e.g. during testing.
200 public static function resetList() {
202 self
::$aliases = null;
206 * Returns a list of canonical special page names.
207 * May be used to iterate over all registered special pages.
211 public static function getNames() {
212 return array_keys( self
::getPageList() );
216 * Get the special page list as an array
218 * @deprecated since 1.24, use getNames() instead.
221 public static function getList() {
222 wfDeprecated( __FUNCTION__
, '1.24' );
223 return self
::getPageList();
227 * Get the special page list as an array
231 private static function getPageList() {
232 global $wgSpecialPages;
233 global $wgDisableInternalSearch, $wgEmailAuthentication;
234 global $wgEnableEmail, $wgEnableJavaScriptTest;
235 global $wgPageLanguageUseDB, $wgContentHandlerUseDB;
237 if ( !is_array( self
::$list ) ) {
238 self
::$list = self
::$coreList;
240 if ( !$wgDisableInternalSearch ) {
241 self
::$list['Search'] = SpecialSearch
::class;
244 if ( $wgEmailAuthentication ) {
245 self
::$list['Confirmemail'] = EmailConfirmation
::class;
246 self
::$list['Invalidateemail'] = EmailInvalidation
::class;
249 if ( $wgEnableEmail ) {
250 self
::$list['ChangeEmail'] = SpecialChangeEmail
::class;
253 if ( $wgEnableJavaScriptTest ) {
254 self
::$list['JavaScriptTest'] = SpecialJavaScriptTest
::class;
257 if ( $wgPageLanguageUseDB ) {
258 self
::$list['PageLanguage'] = SpecialPageLanguage
::class;
260 if ( $wgContentHandlerUseDB ) {
261 self
::$list['ChangeContentModel'] = SpecialChangeContentModel
::class;
264 // Add extension special pages
265 self
::$list = array_merge( self
::$list, $wgSpecialPages );
267 // This hook can be used to disable unwanted core special pages
268 // or conditionally register special pages.
269 Hooks
::run( 'SpecialPage_initList', [ &self
::$list ] );
277 * Initialise and return the list of special page aliases. Returns an array where
278 * the key is an alias, and the value is the canonical name of the special page.
279 * All registered special pages are guaranteed to map to themselves.
282 private static function getAliasList() {
283 if ( is_null( self
::$aliases ) ) {
285 $aliases = $wgContLang->getSpecialPageAliases();
286 $pageList = self
::getPageList();
291 // Force every canonical name to be an alias for itself.
292 foreach ( $pageList as $name => $stuff ) {
293 $caseFoldedAlias = $wgContLang->caseFold( $name );
294 self
::$aliases[$caseFoldedAlias] = $name;
295 $keepAlias[$caseFoldedAlias] = 'canonical';
298 // Check for $aliases being an array since Language::getSpecialPageAliases can return null
299 if ( is_array( $aliases ) ) {
300 foreach ( $aliases as $realName => $aliasList ) {
301 $aliasList = array_values( $aliasList );
302 foreach ( $aliasList as $i => $alias ) {
303 $caseFoldedAlias = $wgContLang->caseFold( $alias );
305 if ( isset( self
::$aliases[$caseFoldedAlias] ) &&
306 $realName === self
::$aliases[$caseFoldedAlias]
308 // Ignore same-realName conflicts
312 if ( !isset( $keepAlias[$caseFoldedAlias] ) ) {
313 self
::$aliases[$caseFoldedAlias] = $realName;
315 $keepAlias[$caseFoldedAlias] = 'first';
318 wfWarn( "First alias '$alias' for $realName conflicts with " .
319 "{$keepAlias[$caseFoldedAlias]} alias for " .
320 self
::$aliases[$caseFoldedAlias]
328 return self
::$aliases;
332 * Given a special page name with a possible subpage, return an array
333 * where the first element is the special page name and the second is the
336 * @param string $alias
337 * @return array Array( String, String|null ), or array( null, null ) if the page is invalid
339 public static function resolveAlias( $alias ) {
341 $bits = explode( '/', $alias, 2 );
343 $caseFoldedAlias = $wgContLang->caseFold( $bits[0] );
344 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
345 $aliases = self
::getAliasList();
346 if ( isset( $aliases[$caseFoldedAlias] ) ) {
347 $name = $aliases[$caseFoldedAlias];
349 return [ null, null ];
352 if ( !isset( $bits[1] ) ) { // T4087
358 return [ $name, $par ];
362 * Check if a given name exist as a special page or as a special page alias
364 * @param string $name Name of a special page
365 * @return bool True if a special page exists with this name
367 public static function exists( $name ) {
368 list( $title, /*...*/ ) = self
::resolveAlias( $name );
370 $specialPageList = self
::getPageList();
371 return isset( $specialPageList[$title] );
375 * Find the object with a given name and return it (or NULL)
377 * @param string $name Special page name, may be localised and/or an alias
378 * @return SpecialPage|null SpecialPage object or null if the page doesn't exist
380 public static function getPage( $name ) {
381 list( $realName, /*...*/ ) = self
::resolveAlias( $name );
383 $specialPageList = self
::getPageList();
385 if ( isset( $specialPageList[$realName] ) ) {
386 $rec = $specialPageList[$realName];
388 if ( is_callable( $rec ) ) {
389 // Use callback to instantiate the special page
390 $page = call_user_func( $rec );
391 } elseif ( is_string( $rec ) ) {
393 $page = new $className;
394 } elseif ( is_array( $rec ) ) {
395 $className = array_shift( $rec );
396 // @deprecated, officially since 1.18, unofficially since forever
397 wfDeprecated( "Array syntax for \$wgSpecialPages is deprecated ($className), " .
398 "define a subclass of SpecialPage instead.", '1.18' );
399 $page = ObjectFactory
::getObjectFromSpec( [
400 'class' => $className,
402 'closure_expansion' => false,
404 } elseif ( $rec instanceof SpecialPage
) {
405 $page = $rec; // XXX: we should deep clone here
410 if ( $page instanceof SpecialPage
) {
413 // It's not a classname, nor a callback, nor a legacy constructor array,
414 // nor a special page object. Give up.
415 wfLogWarning( "Cannot instantiate special page $realName: bad spec!" );
425 * Return categorised listable special pages which are available
426 * for the current user, and everyone.
428 * @param User $user User object to check permissions, $wgUser will be used
430 * @return array ( string => Specialpage )
432 public static function getUsablePages( User
$user = null ) {
434 if ( $user === null ) {
438 foreach ( self
::getPageList() as $name => $rec ) {
439 $page = self
::getPage( $name );
440 if ( $page ) { // not null
441 $page->setContext( RequestContext
::getMain() );
442 if ( $page->isListed()
443 && ( !$page->isRestricted() ||
$page->userCanExecute( $user ) )
445 $pages[$name] = $page;
454 * Return categorised listable special pages for all users
456 * @return array ( string => Specialpage )
458 public static function getRegularPages() {
460 foreach ( self
::getPageList() as $name => $rec ) {
461 $page = self
::getPage( $name );
462 if ( $page && $page->isListed() && !$page->isRestricted() ) {
463 $pages[$name] = $page;
471 * Return categorised listable special pages which are available
472 * for the current user, but not for everyone
474 * @param User|null $user User object to use or null for $wgUser
475 * @return array ( string => Specialpage )
477 public static function getRestrictedPages( User
$user = null ) {
479 if ( $user === null ) {
483 foreach ( self
::getPageList() as $name => $rec ) {
484 $page = self
::getPage( $name );
487 && $page->isRestricted()
488 && $page->userCanExecute( $user )
490 $pages[$name] = $page;
498 * Execute a special page path.
499 * The path may contain parameters, e.g. Special:Name/Params
500 * Extracts the special page name and call the execute method, passing the parameters
502 * Returns a title object if the page is redirected, false if there was no such special
503 * page, and true if it was successful.
505 * @param Title &$title
506 * @param IContextSource &$context
507 * @param bool $including Bool output is being captured for use in {{special:whatever}}
508 * @param LinkRenderer|null $linkRenderer (since 1.28)
512 public static function executePath( Title
&$title, IContextSource
&$context, $including = false,
513 LinkRenderer
$linkRenderer = null
515 // @todo FIXME: Redirects broken due to this call
516 $bits = explode( '/', $title->getDBkey(), 2 );
518 if ( !isset( $bits[1] ) ) { // T4087
524 $page = self
::getPage( $name );
526 $context->getOutput()->setArticleRelated( false );
527 $context->getOutput()->setRobotPolicy( 'noindex,nofollow' );
529 global $wgSend404Code;
530 if ( $wgSend404Code ) {
531 $context->getOutput()->setStatusCode( 404 );
534 $context->getOutput()->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
540 // Narrow DB query expectations for this HTTP request
541 $trxLimits = $context->getConfig()->get( 'TrxProfilerLimits' );
542 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
543 if ( $context->getRequest()->wasPosted() && !$page->doesWrites() ) {
544 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__
);
545 $context->getRequest()->markAsSafeRequest();
549 // Page exists, set the context
550 $page->setContext( $context );
553 // Redirect to canonical alias for GET commands
554 // Not for POST, we'd lose the post data, so it's best to just distribute
555 // the request. Such POST requests are possible for old extensions that
556 // generate self-links without being aware that their default name has
558 if ( $name != $page->getLocalName() && !$context->getRequest()->wasPosted() ) {
559 $query = $context->getRequest()->getQueryValues();
560 unset( $query['title'] );
561 $title = $page->getPageTitle( $par );
562 $url = $title->getFullURL( $query );
563 $context->getOutput()->redirect( $url );
567 $context->setTitle( $page->getPageTitle( $par ) );
569 } elseif ( !$page->isIncludable() ) {
573 $page->including( $including );
574 if ( $linkRenderer ) {
575 $page->setLinkRenderer( $linkRenderer );
578 // Execute special page
585 * Just like executePath() but will override global variables and execute
586 * the page in "inclusion" mode. Returns true if the execution was
587 * successful or false if there was no such special page, or a title object
588 * if it was a redirect.
590 * Also saves the current $wgTitle, $wgOut, $wgRequest, $wgUser and $wgLang
591 * variables so that the special page will get the context it'd expect on a
592 * normal request, and then restores them to their previous values after.
594 * @param Title $title
595 * @param IContextSource $context
596 * @param LinkRenderer|null $linkRenderer (since 1.28)
597 * @return string HTML fragment
599 public static function capturePath(
600 Title
$title, IContextSource
$context, LinkRenderer
$linkRenderer = null
602 global $wgTitle, $wgOut, $wgRequest, $wgUser, $wgLang;
603 $main = RequestContext
::getMain();
605 // Save current globals and main context
609 'request' => $wgRequest,
611 'language' => $wgLang,
614 'title' => $main->getTitle(),
615 'output' => $main->getOutput(),
616 'request' => $main->getRequest(),
617 'user' => $main->getUser(),
618 'language' => $main->getLanguage(),
623 $wgOut = $context->getOutput();
624 $wgRequest = $context->getRequest();
625 $wgUser = $context->getUser();
626 $wgLang = $context->getLanguage();
627 $main->setTitle( $title );
628 $main->setOutput( $context->getOutput() );
629 $main->setRequest( $context->getRequest() );
630 $main->setUser( $context->getUser() );
631 $main->setLanguage( $context->getLanguage() );
634 $ret = self
::executePath( $title, $context, true, $linkRenderer );
636 // Restore old globals and context
637 $wgTitle = $glob['title'];
638 $wgOut = $glob['output'];
639 $wgRequest = $glob['request'];
640 $wgUser = $glob['user'];
641 $wgLang = $glob['language'];
642 $main->setTitle( $ctx['title'] );
643 $main->setOutput( $ctx['output'] );
644 $main->setRequest( $ctx['request'] );
645 $main->setUser( $ctx['user'] );
646 $main->setLanguage( $ctx['language'] );
652 * Get the local name for a specified canonical name
654 * @param string $name
655 * @param string|bool $subpage
658 public static function getLocalNameFor( $name, $subpage = false ) {
660 $aliases = $wgContLang->getSpecialPageAliases();
661 $aliasList = self
::getAliasList();
663 // Find the first alias that maps back to $name
664 if ( isset( $aliases[$name] ) ) {
666 foreach ( $aliases[$name] as $alias ) {
667 $caseFoldedAlias = $wgContLang->caseFold( $alias );
668 $caseFoldedAlias = str_replace( ' ', '_', $caseFoldedAlias );
669 if ( isset( $aliasList[$caseFoldedAlias] ) &&
670 $aliasList[$caseFoldedAlias] === $name
678 wfWarn( "Did not find a usable alias for special page '$name'. " .
679 "It seems all defined aliases conflict?" );
682 // Check if someone misspelled the correct casing
683 if ( is_array( $aliases ) ) {
684 foreach ( $aliases as $n => $values ) {
685 if ( strcasecmp( $name, $n ) === 0 ) {
686 wfWarn( "Found alias defined for $n when searching for " .
687 "special page aliases for $name. Case mismatch?" );
688 return self
::getLocalNameFor( $n, $subpage );
693 wfWarn( "Did not find alias for special page '$name'. " .
694 "Perhaps no aliases are defined for it?" );
697 if ( $subpage !== false && !is_null( $subpage ) ) {
698 // Make sure it's in dbkey form
699 $subpage = str_replace( ' ', '_', $subpage );
700 $name = "$name/$subpage";
703 return $wgContLang->ucfirst( $name );
707 * Get a title for a given alias
709 * @param string $alias
710 * @return Title|null Title or null if there is no such alias
712 public static function getTitleForAlias( $alias ) {
713 list( $name, $subpage ) = self
::resolveAlias( $alias );
714 if ( $name != null ) {
715 return SpecialPage
::getTitleFor( $name, $subpage );